package com.glory.gloryquickui.viewmodel

import android.Manifest
import android.app.Activity
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import com.glory.gloryquickui.base.App
import com.glory.gloryquickui.base.BaseViewModel
import com.glory.gloryquickui.entity.VersionEntity
import com.glory.gloryquickui.model.LoginRepository
import com.glory.gloryquickui.utils.InitUtils
import com.glory.gloryquickui.utils.SharePreferencesUtils
import com.glory.gloryquickui.widget.dialog.FreeUI_DownloadFragmentDialog
import com.google.gson.reflect.TypeToken
import pub.devrel.easypermissions.EasyPermissions
import java.util.HashMap

/**
 * @author HX
 * @date 2021/4/20
 * @desc 业务逻辑
 */
class LoginViewModel : BaseViewModel() {

    private val loginRepository by lazy { LoginRepository() }
    private val PERMISSIONS_REQUEST_CODE = 10
    private var code = 0

    fun login(userName: String, password: String) {
        launchOnlyResult({
            InitUtils.Token = loginRepository.login(userName, password)
            defUI.callObserve.call()
        })
    }

    fun initUser(context: AppCompatActivity){
        InitUtils.BaseUrl = SharePreferencesUtils.getSharePre("GLORY_QUICK_UI_FILE", "BASE_URL", InitUtils.BaseUrl, InitUtils.app)
        InitUtils.FileUrl = SharePreferencesUtils.getSharePre("GLORY_QUICK_UI_FILE", "FILE_URL", InitUtils.FileUrl, InitUtils.app)

        requestPermission(context)
        detectionUpdate(context)

    }

    private fun requestPermission(context: Activity){
        //Manifest.permission.READ_PHONE_STATE 申请不到
        val perms = arrayOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE)
        //权限判断，第一次弹出系统的授权提示框
        if (EasyPermissions.hasPermissions(context, *perms)) {
            //@AfterPermissionGranted 有权限直接执行 todo...

        } else {
            //没有权限的话，先提示，点确定后弹出系统的授权提示框
            EasyPermissions.requestPermissions(context, "程序运行需要权限",
                PERMISSIONS_REQUEST_CODE, *perms)
        }
    }

    private fun detectionUpdate(context: AppCompatActivity) {
        val manager: PackageManager = context.packageManager
        var info: PackageInfo? = null
        try {
            info = manager.getPackageInfo(context.packageName, 0)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        val version = info!!.versionName
        launchOnlyResult({
            //需要使用时打开版本请求
//            val entity: VersionEntity = loginRepository.version()
//            code = compareVersion(version, entity.version)
//            if (code == -1) {
//                val downloadFragmentDialog = FreeUI_DownloadFragmentDialog()
//                downloadFragmentDialog.setData(entity)
//                downloadFragmentDialog.show(context.supportFragmentManager, "DOWNLOAD")
//            }
        })

    }

    private fun compareVersion(version1: String, version2: String): Int {
        return if (version1 == version2) {
            0
        } else {
            val version1Array = version1.split("\\.".toRegex()).toTypedArray()
            val version2Array = version2.split("\\.".toRegex()).toTypedArray()
            var index = 0
            val minLen = Math.min(version1Array.size, version2Array.size)
            var diff = 0
            while (index < minLen && version1Array[index].toInt() - version2Array[index].toInt().also { diff = it } == 0) {
                ++index
            }
            if (diff == 0) {
                var i: Int = index
                while (i < version1Array.size) {
                    if (version1Array[i].toInt() > 0) {
                        return 1
                    }
                    ++i
                }
                i = index
                while (i < version2Array.size) {
                    if (version2Array[i].toInt() > 0) {
                        return -1
                    }
                    ++i
                }
                0
            } else {
                if (diff > 0) 1 else -1
            }
        }
    }
}